package com.lgt_enterprise_android.view.pages;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.fastjson.JSONArray;
import com.bumptech.glide.Glide;
import com.lgt_enterprise_android.R;
import com.lgt_enterprise_android.base.BaseActivity;
import com.lgt_enterprise_android.utils.StringUtil;
import com.lgt_enterprise_android.view.widgets.HackyViewPager;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;

import uk.co.senab.photoview.PhotoView;


public class ImageLookingActivity extends BaseActivity {

    //    private static final String STATE_POSITION = "STATE_POSITION";
    public static final String EXTRA_IMAGE_INDEX = "image_index";
//    public static final String EXTRA_IMAGE_URLS = "image_urls";

    private HackyViewPager mPager;
    private static int currentPagerPosition;

    private TextView mTxtIndex;

    ArrayList<String> list;

    private boolean isEdit = false;
    private Context mContext;

    private ViewGroup viewGroup;

    private RelativeLayout rel;


    private String order_id;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        statusBarColor = R.color.black;
        isDarkfont = false;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image_detail_pager);
        mContext = this;
        mTxtIndex = (TextView) findViewById(R.id.txt_index);
        mPager = (HackyViewPager) findViewById(R.id.pager);
        isEdit = getIntent().hasExtra("isEdit");
        viewGroup = (ViewGroup) (findViewById(R.id.img_container));

        order_id = getIntent().getStringExtra("order_no");

        currentPagerPosition = getIntent().getIntExtra(EXTRA_IMAGE_INDEX, 0);

        String str = getIntent().getStringExtra("imgsStr");

        if (StringUtil.isEmpty(str)) {
            finish();
            return;
        }

        JSONArray jsonArray = JSONArray.parseArray(str);

        list = new ArrayList<String>();

        for (int i = 0; i < jsonArray.size(); i++) {
            list.add(jsonArray.getString(i));
        }


        setEvent();
        setIndexTitle();

        mPager.setAdapter(new SamplePagerAdapter(this, list, null));
        mPager.setCurrentItem(currentPagerPosition);
    }


    private void setIndexTitle() {
        mTxtIndex.setText((currentPagerPosition + 1) + "/" + list.size());
    }

    private void setEvent() {
        findViewById(R.id.txt_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        // 更新下标
        mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageSelected(int arg0) {
                currentPagerPosition = arg0;
                setIndexTitle();

                if (isEdit) {
                    int count = viewGroup.getChildCount();
                    if (count > 1) {
                        for (int i = count; i > 1; i--) {
                            viewGroup.removeViewAt(i - 1);
                        }
                    }
                }

            }

        });
    }

    static class SamplePagerAdapter extends PagerAdapter {
        final String[] items = new String[]{"保存图片"};
        final Bitmap[] bitmap = new Bitmap[1];

        View.OnTouchListener onTouchListener;

        private Context mContext;

        interface ITouchCallback {
            void invoke(MotionEvent event);

            void clean();
        }

        ITouchCallback callback;

        private ArrayList<String> mStringArrayList;

        public SamplePagerAdapter(Context _context, ArrayList<String> list, ITouchCallback _callback) {
            mContext = _context;
            this.callback = _callback;
            mStringArrayList = list;
        }

        @Override
        public int getCount() {
            return mStringArrayList.size();
        }

        @Override
        public View instantiateItem(ViewGroup container, int position) {
            //定义可以缩放的图片对象
            PhotoView photoView = new PhotoView(container.getContext());

            photoView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                    builder.setItems(items, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            saveImageToGallery(mContext, bitmap[0]);

                        }
                    });
                    builder.show();
                    return true;
                }
            });

//            if (callback != null) {
//
//                callback.clean();
//
//                photoView.setOnTouchListener(new View.OnTouchListener() {
//                    @Override
//                    public boolean onTouch(View v, MotionEvent event) {
//                        if (event.getAction() == MotionEvent.ACTION_UP) {
//                            callback.invoke(event);
//                        }
//                        return true;
//                    }
//                });
//            }


            Glide.with(container.getContext()).load(mStringArrayList.get(position)).into(photoView);
            // Now just add PhotoView to ViewPager and return it
            container.addView(photoView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);


            return photoView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        public static void saveImageToGallery(Context context, Bitmap bmp) {

            // 首先保存图片 创建文件夹
            File appDir = new File(Environment.getExternalStorageDirectory(), "shy");
            if (!appDir.exists()) {
                appDir.mkdir();
            }
            //图片文件名称
            String fileName = "shy_" + System.currentTimeMillis() + ".jpg";
            File file = new File(appDir, fileName);
            try {
                FileOutputStream fos = new FileOutputStream(file);
                bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                fos.flush();
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            // 其次把文件插入到系统图库
            String path = file.getAbsolutePath();
            try {
                MediaStore.Images.Media.insertImage(context.getContentResolver(), path, fileName, null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            // 最后通知图库更新
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(file);
            intent.setData(uri);
            context.sendBroadcast(intent);
            Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();
        }

    }

    private String viewSaveToImage(View view) {
        view.setDrawingCacheEnabled(true);
        view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        view.setDrawingCacheBackgroundColor(Color.WHITE);

        // 把一个View转换成图片
        Bitmap cachebmp = loadBitmapFromView(view);

        FileOutputStream fos;
        String imagePath = "";
        try {
            File sdRoot = mContext.getExternalCacheDir();
            File file = new File(sdRoot, System.currentTimeMillis() + ".png");

            if (!file.exists()) {
                file.createNewFile();
            }

            fos = new FileOutputStream(file);
            imagePath = file.getAbsolutePath();

            cachebmp.compress(Bitmap.CompressFormat.PNG, 100, fos);

            fos.flush();
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        view.destroyDrawingCache();

        return imagePath;
    }


    private Bitmap loadBitmapFromView(View v) {
        int w = v.getWidth();
        int h = v.getHeight();

        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色，则生成透明 */

        v.layout(0, 0, w, h);
        v.draw(c);

        return bmp;
    }
}